<template>
  <div class="payment-success">
    <div class="success-icon">
      <i class="el-icon-success"></i>
    </div>
    <h1>支付成功</h1>
    <p>您的缴费已处理成功，感谢您的支付！</p>
    <p>页面将在 <span>{{ countdown }}</span> 秒后自动关闭</p>
    <div class="buttons">
      <el-button type="primary" @click="backToPayList">返回缴费列表</el-button>
      <el-button @click="closeWindow">关闭窗口</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import http from '@/api/http.js'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const countdown = ref(5)
let timer: any = null

// 解析URL参数
const getQueryParams = () => {
  const queryString = window.location.search
  console.log('URL查询字符串:', queryString) // 调试信息
  const urlParams = new URLSearchParams(queryString)
  
  // 从支付宝回调参数中获取
  const patientCode = urlParams.get('patientCode') 
  const outTradeNo = urlParams.get('out_trade_no')
  const tradeNo = urlParams.get('trade_no')
  const id = urlParams.get('id') // 新增：获取记录ID
  
  // 从localStorage中获取之前存储的patientCode和id作为备用
  const savedPatientCode = localStorage.getItem('currentPatientCode')
  const savedId = localStorage.getItem('currentPaymentId')
  
  console.log('解析参数:', { patientCode, outTradeNo, tradeNo, id, savedPatientCode, savedId }) // 调试信息
  
  return {
    id: id || savedId, // 支付记录ID
    patientCode: patientCode || outTradeNo || savedPatientCode, // 优先使用URL参数，然后是localStorage
    orderNo: outTradeNo,
    tradeNo: tradeNo
  }
}

// 更新支付状态
const updatePaymentStatus = async () => {
  const params = getQueryParams()
  
  // 尝试使用ID更新（优先）
  if (params.id) {
    try {
      console.log('使用ID更新支付状态:', params.id)
      const response = await http.post(`/api/PayConfirmController/UpdatePayStatus?id=${params.id}&isPay=1`)
      console.log('ID更新支付状态响应:', response)
      ElMessage.success('支付状态已更新')
      return
    } catch (error) {
      console.error('使用ID更新支付状态失败:', error)
      // 继续尝试使用orderNo更新
    }
  }
  
  // 使用patientCode或orderNo作为订单号
  const orderNo = params.patientCode || params.orderNo
  
  if (!orderNo) {
    ElMessage.warning('缺少必要的支付信息')
    console.error('缺少订单号，无法更新支付状态')
    return
  }
  
  console.log('准备使用orderNo更新支付状态，订单号:', orderNo) // 调试信息
  
  try {
    // 调用更新支付状态的API - 明确设置isPay=1表示已支付
    const response = await http.post(`/api/PayConfirmController/UpdatePaymentStatus?orderNo=${orderNo}&isPay=1`)
    console.log('更新支付状态响应:', response) // 调试信息
    ElMessage.success('支付状态已更新')
    
    // 清除localStorage中的临时数据
    localStorage.removeItem('currentPatientCode')
    localStorage.removeItem('currentPaymentId')
  } catch (error) {
    console.error('更新支付状态失败:', error)
    ElMessage.error('更新支付状态失败')
  }
}

// 返回缴费列表并确保刷新
const backToPayList = () => {
  // 设置一个标记，告诉缴费列表页面需要刷新数据
  localStorage.setItem('refreshPaymentList', 'true')
  
  // 使用replace而不是push，防止返回到支付结果页
  router.replace('/PayInfo')
}

// 关闭窗口
const closeWindow = () => {
  window.close()
}

// 倒计时关闭
const startCountdown = () => {
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      closeWindow()
    }
  }, 1000)
}

onMounted(async () => {
  // 更新支付状态
  await updatePaymentStatus()
  // 开始倒计时
  startCountdown()
  
  // 将成功状态广播给所有打开的窗口
  try {
    if (window.opener && !window.opener.closed) {
      // 向父窗口发送支付成功消息
      window.opener.postMessage({ type: 'PAYMENT_SUCCESS' }, '*')
    }
  } catch (e) {
    console.log('通知父窗口失败:', e)
  }
})

onBeforeUnmount(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.payment-success {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  text-align: center;
  min-height: 60vh;
}

.success-icon {
  font-size: 64px;
  color: #67C23A;
  margin-bottom: 20px;
}

h1 {
  color: #67C23A;
  font-size: 28px;
  margin-bottom: 10px;
}

p {
  font-size: 16px;
  margin-bottom: 20px;
  color: #606266;
}

.buttons {
  margin-top: 20px;
  display: flex;
  gap: 15px;
}

span {
  font-weight: bold;
  color: #409EFF;
}
</style>